package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;

/**
 * 蓝牙钥匙设置
 */
public class BsSpeedLimitActivity extends RootActivity {
    private static final String TAG = "BsSpeedLimitActivity";

    private ImageView iv_bluetooth_key_back;

    private TextView tv_speed_limit_25;
    private TextView tv_speed_limit_32;

    private RelativeLayout rl_cover;

    private HandleDataByBLEUtil handleDataByBLEUtil;

    private BluetoothKeyHandleDataFromBleReceiver bluetoothKeyHandleDataFromBleReceiver;

    private AlertDialog speedLimitDialog;

    private Integer limitAmount = 32;

    private Integer initLimitAmount = 0;

    private boolean isWriteAble = true;

    private boolean isQuery = true;

    //等待回馈
    private Handler waitHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (View.VISIBLE == rl_cover.getVisibility()) {
                rl_cover.setVisibility(View.GONE);

                if (isQuery) {
                    Toast.makeText(getApplicationContext(), ToastConstant.QUERY_FAILURE, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), ToastConstant.MODIFY_FAILURE, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bs_speed_limit);

        initView();
        initViewListener();
        initSpeedLimitDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播
        bluetoothKeyHandleDataFromBleReceiver = new BluetoothKeyHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(bluetoothKeyHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);

        initViewContent();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //回收广播接收者
        unregisterReceiver(bluetoothKeyHandleDataFromBleReceiver);
    }

    /***********************************************************************************************/
    /**                                 初始化控件对象 监听 控件内容方法                             **/
    /***********************************************************************************************/

    private void initView() {
        iv_bluetooth_key_back = (ImageView) findViewById(R.id.iv_bluetooth_key_back);

        tv_speed_limit_25 = (TextView) findViewById(R.id.tv_speed_limit_25);
        tv_speed_limit_32 = (TextView) findViewById(R.id.tv_speed_limit_32);
        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);
    }

    private void initViewListener() {
        //回退事件监听
        iv_bluetooth_key_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //添加速度限制25km/h
        tv_speed_limit_25.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                limitAmount = 25;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                });
            }
        });

        //添加速度限制32km/h
        tv_speed_limit_32.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                limitAmount = 32;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                });
            }
        });
    }

    private void initViewContent() {

        //初始化限速数据 默认为32
        limitAmount = 32;
        //初始化读失败可以写一次
        isWriteAble = true;

        //查询第一个寄存器数据
        handleDataByBLEUtil.sendDataToDevice("t|r,229");
        isQuery = true;

//        waitHandle.sendEmptyMessageDelayed(0, 10* 1000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(10 * 1000);

                if (View.VISIBLE == rl_cover.getVisibility()) {
                    rl_cover.setVisibility(View.GONE);
                    try {
                        if (isQuery) {
                            Toast.makeText(getApplicationContext(), ToastConstant.QUERY_FAILURE, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), ToastConstant.MODIFY_FAILURE, Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 修改第一个寄存器数据
     */
    private void sendSpeedLimitInstruction() {
        if (isWriteAble) {
            handleDataByBLEUtil.sendDataToDevice("t|w,229," + limitAmount * 256);
            isWriteAble = false;
            isQuery = false;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(10 * 1000);

                    if (View.VISIBLE == rl_cover.getVisibility()) {
                        rl_cover.setVisibility(View.GONE);

                        if (isQuery) {
                            Toast.makeText(getApplicationContext(), ToastConstant.QUERY_FAILURE, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), ToastConstant.MODIFY_FAILURE, Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }).start();
        }
    }

    /**
     * 更新限速展示
     */
    private void refreshText(Integer speedTag) {
        if (25 == speedTag) {
            tv_speed_limit_25.setTextColor(getResources().getColor(R.color.white));
            tv_speed_limit_25.setBackground(getDrawable(R.drawable.shape_btn_bg_left_check));

            tv_speed_limit_32.setTextColor(getResources().getColor(R.color.black));
            tv_speed_limit_32.setBackground(getDrawable(R.drawable.shape_btn_bg_right_un_check));
        } else {
            tv_speed_limit_25.setTextColor(getResources().getColor(R.color.black));
            tv_speed_limit_25.setBackground(getDrawable(R.drawable.shape_btn_bg_left_un_check));

            tv_speed_limit_32.setTextColor(getResources().getColor(R.color.white));
            tv_speed_limit_32.setBackground(getDrawable(R.drawable.shape_btn_bg_right_check));
        }

        rl_cover.setVisibility(View.GONE);
    }

    /***********************************************************************************************/
    /**                                 自定义广播接收者类                                          **/
    /***********************************************************************************************/
    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class BluetoothKeyHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            if (result.contains("t|w,229," + limitAmount * 256)) {
                SystemClock.sleep(500);

                //修改第二个寄存器数据
                handleDataByBLEUtil.sendDataToDevice("t|w,236," + limitAmount * 256);
                return;
            }

            if (result.contains("t|w,236," + limitAmount * 256)) {
                SystemClock.sleep(500);

                //保存flash
                handleDataByBLEUtil.sendDataToDevice("t|w,511,32767");

                //隔三秒重新读一下
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(3000);
                        handleDataByBLEUtil.sendDataToDevice("t|r,229");
                    }
                }).start();

                return;
            }

            //更新界面 写入成功
            if (result.contains("t|w,511,4096")) {
                refreshText(limitAmount);
                return;
            }

            //更新界面 写入失败
            if (result.contains("t|w,511,8192")) {
                Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_SPEED_LIMIT_FAILURE, Toast.LENGTH_SHORT).show();
                return;
            }

            //查询第二个寄存器数据
            if (result.contains("t|r,229")) {
                if (result.contains(25 * 256 + "")) {
                    initLimitAmount = 25;
                    handleDataByBLEUtil.sendDataToDevice("t|r,236");
                } else if (result.contains(32 * 256 + "")) {
                    initLimitAmount = 32;
                    handleDataByBLEUtil.sendDataToDevice("t|r,236");
                } else {
                    sendSpeedLimitInstruction();
                }
                return;
            }

            //查询第二个寄存器数据
            if (result.contains("t|r,236")) {
                if (result.contains(initLimitAmount * 256 + "")) {
                    refreshText(initLimitAmount);
                } else {
                    sendSpeedLimitInstruction();
                }
                return;
            }
        }
    }

    /***********************************************************************************************/
    /**                                  初始化dialog弹出框                                        **/
    /***********************************************************************************************/
    /**
     * 初始化提示消息弹窗
     */
    private void initSpeedLimitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Notice");
        builder.setMessage("Please comply with your local laws and regulations about speed limit.");

        //取消修改限速
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismissDialog();
            }
        });

        //用户自己设置速度
        builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sendSpeedLimitInstruction();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        rl_cover.setVisibility(View.VISIBLE);
                    }
                });
            }
        });

        //创建弹出框
        speedLimitDialog = builder.create();
    }

    //隐藏弹出框
    private void dismissDialog() {
        if (null != speedLimitDialog) {
            speedLimitDialog.dismiss();
        }
    }

    //展示弹出框
    private void showDialog() {
        if (null != speedLimitDialog && !speedLimitDialog.isShowing()) {
            speedLimitDialog.show();
        }
    }
}
